package com.chuangke.common.db.mybatis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class XMLGregorianCalendarTypeHandler extends BaseTypeHandler<XMLGregorianCalendar> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, XMLGregorianCalendar parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setTimestamp(i, new Timestamp(parameter.toGregorianCalendar().getTime().getTime()));
	}

	@Override
	public XMLGregorianCalendar getNullableResult(ResultSet rs, String columnName) throws SQLException {
		Timestamp sqlTimestamp = rs.getTimestamp(columnName);
		if (sqlTimestamp != null) {
			
			return getXMLGregorianCalendar(new Date(sqlTimestamp.getTime()));
		}
		return null;
	}

	@Override
	public XMLGregorianCalendar getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
		if (sqlTimestamp != null) {
			return getXMLGregorianCalendar(new Date(sqlTimestamp.getTime()));
		}
		return null;
	}

	@Override
	public XMLGregorianCalendar getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
		if (sqlTimestamp != null) {
			return getXMLGregorianCalendar(new Date(sqlTimestamp.getTime()));
		}
		return null;
	}
	
	private XMLGregorianCalendar getXMLGregorianCalendar(Date date) {
		GregorianCalendar gdate = new GregorianCalendar();
		gdate.setTime(date);
		try {
			return DatatypeFactory.newInstance().newXMLGregorianCalendar(gdate);
		} catch (DatatypeConfigurationException e) {
			throw new RuntimeException(e);
		}
	}

}
